<template>
  <div class="products">
    <div class="title">团购商品</div>

    <template v-for="(item, index) in products" :key="item.id">
      <product-item
        ref="itemRef"
        :product-detail="item"
        :num="index + 1"
        :is-dis-move-up="isDisMoveTool('up', item.id)"
        :is-dis-move-down="isDisMoveTool('down', item.id)"
        @del-product="handleDelProduct"
        @move="handleMove"
      />
    </template>

    <div class="action">
      <button class="action-btn" @click="handleAddProduct">
        <span class="icon" :class="{ 'icon-move': isIOS }">+</span> 添加商品
      </button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import ProductItem from './product-item.vue'
  import { nanoid } from 'nanoid'
  import { ref, onBeforeUnmount, nextTick } from 'vue'
  import { judgeClient } from '@/utils/utils'
  import { onActivated } from 'vue'
  const { isIOS } = judgeClient()

  // - data
  const products = ref<any[]>([])
  const itemRef = ref<InstanceType<typeof ProductItem>>()

  // - methods
  const isDisMoveTool = (type: string, id: any) => {
    const index = products.value.findIndex((item) => item.id == id)

    if (type == 'up') {
      return index == 0 ? true : false
    } else {
      return index == products.value.length - 1 ? true : false
    }
  }
  const handleAddProduct = () => {
    products.value.push({
      id: nanoid(),
      name: '',
      desc: '',
      specs: '',
      price: '',
      stock: '',
      crossedPrice: '',
      costPrice: ''
    })
  }
  const handleDelProduct = (id: any) => {
    products.value = [...products.value.filter((item) => item.id != id)]

    // window.localStorage.removeItem(`productsItem-${id}`) // 商品item
    window.localStorage.removeItem(`productDesc-${id}`) // 描述item
  }
  const handleMove = ({ type, id }: any) => {
    const index = products.value.findIndex((item) => item.id == id)
    const item = products.value.find((item) => item.id == id) as any
    products.value.splice(index, 1)

    if (type == 'up') {
      products.value.splice(index - 1, 0, item)
    } else {
      products.value.splice(index + 1, 0, item)
    }
  }
  const handleCommit = async () => {
    if (itemRef.value instanceof Array) {
      const arr: any[] = []
      for (const item of itemRef.value) {
        const res = await item?.submit()
        arr.push(res)
      }
      return arr
    }
  }

  // - lifecycle
  // function init() {
  //   const localProducts = window.localStorage.getItem('products')
  //   if (localProducts) {
  //     const arr = JSON.parse(localProducts)
  //     if (arr.length > 0) {
  //       products.value = arr
  //     } else {
  //       handleAddProduct()
  //     }
  //   } else {
  //     handleAddProduct()
  //   }
  // }
  // init()
  // onBeforeUnmount(() => {
  //   products.value && window.localStorage.setItem('products', JSON.stringify(products.value))
  // })
  onActivated(() => {
    if (products.value.length <= 0) {
      handleAddProduct()
    }
  })

  // - expose
  const resetData = () => {
    products.value.forEach((item) => {
      window.localStorage.removeItem(`productDesc-${item.id}`) // 描述item
    })
    products.value = []
  }
  defineExpose({ handleCommit, itemRef, resetData })
</script>

<style lang="scss" scoped>
  .products {
    background-color: #ffffff;
    margin-top: 20px;
    padding: 0 20px;
    border-radius: 20px;
    overflow: hidden;

    .title {
      display: flex;
      align-items: center;
      height: 90px;
      font-size: 32px;
      font-family: PingFang-SC-Medium, PingFang-SC;
      font-weight: 500;
      color: #000000;
    }

    .action {
      display: flex;
      justify-content: center;
      padding-bottom: 25px;

      .action-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 630px;
        height: 90px;
        border-radius: 16px;
        border: 1px solid #40ae36;
        font-size: 40px;
        font-family: PingFang-SC-Regular, PingFang-SC;
        font-weight: 400;
        color: #40ae36;
        background: none;

        .icon {
          margin-right: 10px;
        }
        .icon-move {
          transform: translateY(-3px);
        }
      }
    }
  }
</style>
